package com.tdu.spider.biz.service.jike;

import com.tdu.spider.biz.service.jike.vo.MessageQueryVO;
import com.tdu.spider.dao.JkCategoryRepository;
import com.tdu.spider.dao.JkMessageRepository;
import com.tdu.spider.dao.JkTopicRepository;
import com.tdu.spider.model.JkCategoryDO;
import com.tdu.spider.model.JkMessageDO;
import com.tdu.spider.model.JkTopicDO;
import com.tdu.spider.model.JkUserInfoDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class JikeService {
    private static final Logger  logger = LoggerFactory.getLogger(JikeService.class);

    @Autowired
    private JkTopicRepository    jkTopicRepository;

    @Autowired
    private JkMessageRepository  jkMessageRepository;

    @Autowired
    private JkCategoryRepository jkCategoryRepository;

    @Autowired
    private JikeApiService       jikeApiService;

    
    public boolean updateTopic() throws Exception {
        //step1:删除所有我关注频道
        jkTopicRepository.deleteAll();
        //step2:获取我关注的频道
        JkUserInfoDO userInfo = jikeApiService.getUserInfo();
        int page = userInfo.getStatsCount().getTopicSubscribed() % 20 == 0 ? userInfo.getStatsCount().getTopicSubscribed() / 20
                : userInfo.getStatsCount().getTopicSubscribed() / 20 + 1;
        for(int i=0;i<page;i++){
            List<JkTopicDO> topicVOS = jikeApiService.getMyTopic(i*20);
            jkTopicRepository.saveAll(topicVOS);
        }
        return true;
    }

    public boolean updateCategorys() throws Exception {
        List<JkCategoryDO> categorys = jikeApiService.getCategory();
        jkCategoryRepository.saveAll(categorys);
        return true;
    }

    
    public boolean updateBestTopic() throws Exception {
        List<JkCategoryDO> categoryDOS = jkCategoryRepository.findAll();

        for (JkCategoryDO categoryDO : categoryDOS) {
            logger.info("run categoryId:{},name:{},count:{}", categoryDO.getId(),
                categoryDO.getName(), categoryDO.getCount());
            int page = categoryDO.getCount() % 20 == 0 ? categoryDO.getCount() / 20
                : categoryDO.getCount() / 20 + 1;
            for (int i = 1; i < page; i++) {
                List<JkTopicDO> jkTopicDOS = jikeApiService.queryTopic(categoryDO.getId(), i * 20);
                for (JkTopicDO topicDO : jkTopicDOS) {
                    if (topicDO.getSubscribersCount() > 10000) {
                        boolean flag = jikeApiService.subscribedTopic(topicDO.getId());
                        logger.info("than {},count:{},result:{}", topicDO.getContent(),
                            topicDO.getSubscribersCount(), flag);
                    }
                }
                logger.info("count:{},page:{},run:{}", jkTopicDOS.size(), page, i);
            }
        }
        return true;
    }

    
    public boolean updateMessage() throws Exception {
        long start = System.currentTimeMillis();
        for(int j=1;j<79;j++) {
            Pageable pageable = PageRequest.of(j, 10, Sort.Direction.DESC, "topicId");
            Page<JkTopicDO> doPage = jkTopicRepository.findAll(pageable);
            for (JkTopicDO jkTopicDO : doPage.getContent()) {
                logger.info("updateMessage_start-{}", jkTopicDO.getContent());
                MessageQueryVO messageQueryVO = new MessageQueryVO();
                messageQueryVO.setLimit(20);
                messageQueryVO.setTopic(jkTopicDO.getId());
                List<JkMessageDO> messageVOList = jikeApiService.queryMessage(messageQueryVO);
                jkMessageRepository.saveAll(messageVOList);
                if (CollectionUtils.isEmpty(messageVOList)) {
                    return false;
                }
                int cot = 0;
                long _start = System.currentTimeMillis();
                while (true) {
                    TimeUnit.SECONDS.sleep(2);
                    messageQueryVO.setMessageIdLessThan(
                            messageVOList.get(messageVOList.size() - 1).getMessageId());
                    messageVOList = jikeApiService.queryMessage(messageQueryVO);
                    //logger.info("get {}", messageQueryVO.getMessageIdLessThan());
                    if (CollectionUtils.isEmpty(messageVOList)) {
                        break;
                    }
                    jkMessageRepository.saveAll(messageVOList);
                    cot += messageVOList.size();
                }
                TimeUnit.MINUTES.sleep(2);
                logger.info("updateMessage_end-{}---cost:{}---topicId:{}---cot:{}", jkTopicDO.getContent(),
                        (System.currentTimeMillis() - _start) / 1000, jkTopicDO.getTopicId(), cot);
            }
        }

        logger.info("success-cost:{}", (System.currentTimeMillis() - start) / 1000);
        return true;
    }

    
    public boolean daliyUpdate() throws Exception {
        List<JkTopicDO> jkTopicDOS = jkTopicRepository.findAll();
        for (JkTopicDO jkTopicDO : jkTopicDOS) {
            TimeUnit.SECONDS.sleep(10);
            MessageQueryVO messageQueryVO = new MessageQueryVO();
            messageQueryVO.setLimit(30);
            messageQueryVO.setTopic(jkTopicDO.getId());
            List<JkMessageDO> messageVOList = jikeApiService.queryMessage(messageQueryVO);
            logger.info("update topic:{},topicId:{},cot:{}",jkTopicDO.getContent(),jkTopicDO.getTopicId(),messageVOList.size());
            if (CollectionUtils.isEmpty(messageVOList)) {
                break;
            }
            jkMessageRepository.saveAll(messageVOList);
        }
        logger.info("update successTopicCot:{}",jkTopicDOS.size());
        return false;
    }
}
